#!/bin/bash/python
# _*_ coding: utf-8 _*_
# file： check_getcmd
# date-time: 2023/7/1-11:00
# auth:hard work
# description
import threading
import time

from pythonping import ping

from scapy.layers.inet import IP, ICMP
from scapy.sendrecv import sr1

from utils.get_local_ip import get_host_ip


def check_host_stat1(dst_ip):
    # 设置源 IP 地址和目的 IP 地址
    src_ip = get_host_ip()
    # dst_ip = "192.168.10.1"

    # 创建 ICMP 数据包
    pkt = IP(src=src_ip, dst=dst_ip) / ICMP()

    # 发送数据包并等待回复
    response = sr1(pkt, timeout=2, verbose=0)

    # 判断是否收到回复
    if response:
        # print("目标 IP 地址 {} 存活".format(dst_ip))
        print(dst_ip + " is reachable.")
        return True
    else:
        # print("目标 IP 地址 {} 不存活".format(dst_ip))
        print(dst_ip + " is not reachable.")
        return False

def check_host_stat(host):
    try:
        ping_result = ping(target=host, timeout=2)
        # pythonping如果能够ping通，返回值内有Reply这个字符串，失败时则没有。我们可以通过这个不同来打印出最后的结果
        if "Reply" in str(ping_result):
            print(host + " is reachable.")
            return True
        else:
            print(host + " is not reachable.")
            return False
    except TimeoutError:
        print('time out')
    except Exception as e:
        print(e)


def func2(ip):
    for i in ip:
        check_host_stat1(i)


def main():
    ip = "10.11.0.{}"
    ip_lst2 = []
    ip_lst3 = []
    ip_lst4 = []
    ip_lst5 = []
    ip_lst6 = []
    for i in range(2, 254):
        if i < 40:
            ip_lst2.append(ip.format(i))
        elif i < 80:
            ip_lst3.append(ip.format(i))
        elif i < 160:
            ip_lst4.append(ip.format(i))
        elif i < 200:
            ip_lst5.append(ip.format(i))
        else:
            ip_lst6.append(ip.format(i))

    threads = []  # 定义一个线程池
    t1 = threading.Thread(target=func2, args=[ip_lst2])
    threads.append(t1)  # 把t1线程装到线程池里
    t2 = threading.Thread(target=func2, args=[ip_lst3])
    threads.append(t2)  # 把t2线程装到线程池里
    t3 = threading.Thread(target=func2, args=[ip_lst4])
    threads.append(t3)  # 把t2线程装到线程池里
    t4 = threading.Thread(target=func2, args=[ip_lst5])
    threads.append(t4)  # 把t2线程装到线程池里
    t5 = threading.Thread(target=func2, args=[ip_lst6])
    threads.append(t5)  # 把t2线程装到线程池里
    start = time.time()
    print(f"start_time:{start}\n")
    for t in threads:
        t.start()
        # t.run()
        endtime = time.time() - start
        print("\nendtime:", time.time())
        print("all_execute_time:", endtime)


if __name__ == '__main__':
    try:
        main()
    except RuntimeError:
        pass
